﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;

using SharedGenomics.Core;

namespace SharedGenomics.Workbench.Core
{
    public class DynamicTypeMapper
    {
        private IList<ITypeMappingStrategy> _strategies;

        public DynamicTypeMapper(IUnityContainer container)
        {
            container.ThrowIfNull("container");
            this.Container = container;
            this._strategies = new List<ITypeMappingStrategy>();
        }

        public void AddMappingStrategy<TMappingStrategy>() where TMappingStrategy : ITypeMappingStrategy, new()
        {
            this.AddMappingStrategy(new TMappingStrategy());
        }

        public void AddMappingStrategy(ITypeMappingStrategy strategy)
        {
            strategy.ThrowIfNull("strategy");
            this._strategies.Add(strategy);
        }

        public void AddMappings(IEnumerable<Type> types)
        {
            Dictionary<Type, Type> mappings = new Dictionary<Type,Type>();

            foreach (Type t in types ?? Enumerable.Empty<Type>())
            {
                foreach (var mappingStrategy in this._strategies)
                {
                    mappingStrategy.ExamineType(t, mappings);
                }
            }

            foreach (var map in mappings)
            {
                this.Container.RegisterType(map.Key, map.Value);
            }
        }

        private IUnityContainer Container { get; set; }
    }
}
